//
//  TSFileTools.m
//  chart
//
//  Created by 曾斌 on 15/11/8.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSFileTools.h"
#import <AFNetworking.h>

@implementation TSFileTools
/**
 * 下载文件
 */
+(void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName tag:(NSInteger)aTag
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //检查本地文件是否已存在
    NSString *fileName = [NSString stringWithFormat:@"%@/%@", aSavePath, aFileName];
    
    //检查附件是否存在
    if ([fileManager fileExistsAtPath:fileName]) {
        NSData *audioData = [NSData dataWithContentsOfFile:fileName];
//        [self requestFinished:[NSDictionary dictionaryWithObject:audioData forKey:@"res"] tag:aTag];
    }else{
        //创建附件存储目录
        if (![fileManager fileExistsAtPath:aSavePath]) {
            [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //下载附件
        NSURL *url = [[NSURL alloc] initWithString:aUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.inputStream   = [NSInputStream inputStreamWithURL:url];
        operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];
        
        //下载进度控制
        /*
         [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
         NSLog(@"is download：%f", (float)totalBytesRead/totalBytesExpectedToRead);
         }];
         */
        
        //已完成下载
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSData *audioData = [NSData dataWithContentsOfFile:fileName];
            
                  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            //下载失败
        //    [self requestFailed:aTag];
        }];
        
        [operation start];
    }
}
+(NSString *)getCacheFileDir
{
    return @"/affairs";
}


#pragma mark 下载
+ (void)download:(NSString *) urlStr name:(NSString *)fileName downloadHandler:(DownloadHandler)handler
{
    NSURL *url = [NSURL URLWithString:urlStr];
    AFHTTPRequestOperationManager *_operationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
    NSOperationQueue *_queue = [[NSOperationQueue alloc] init];
    // 1. 建立请求
    
    NSURLRequest *request = [_operationManager.requestSerializer requestWithMethod:@"GET" URLString:urlStr parameters:nil error:nil];
   
    // 2. 操作
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    AFHTTPRequestOperation *_downloadOperation = op;
    
    // 下载
    // 指定文件保存路径，将文件保存在沙盒中
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docs[0] stringByAppendingPathComponent:fileName];
    
    op.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    
    // 设置下载进程块代码
    /*
     bytesRead                      当前一次读取的字节数(100k)
     totalBytesRead                 已经下载的字节数(4.9M）
     totalBytesExpectedToRead       文件总大小(5M)
     */
    [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
        // 设置进度条的百分比
        CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
        NSLog(@"%f", precent);
        
       // _progressView.progress = precent;
    }];
    
    // 设置下载完成操作
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 下载完成之后，解压缩文件
        /*
         参数1:要解结压缩的文件名及路径 path - > download.zip
         参数2:要解压缩到的位置，目录    - > document目录
         */
        
        // 解压缩之后，将原始的压缩包删除
        // NSFileManager专门用于文件管理操作，可以删除，复制，移动文件等操作
        // 也可以检查文件是否存在
        
        // 下一步可以进行进一步处理，或者发送通知给用户。
        NSLog(@"下载成功");
        handler(path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
    
    // 启动下载
    [_operationManager.operationQueue addOperation:op];
}

+(void)openMenu:(UIView *)view delete:(id)dele filePath:(NSString *)path
{
    NSString * mpath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
    
    UIDocumentInteractionController *documentController =
    
    [UIDocumentInteractionController
     
    interactionControllerWithURL:[NSURL fileURLWithPath:mpath]];
    
    
    documentController.delegate=dele;
    
    [documentController presentOpenInMenuFromRect:CGRectMake(760, 20, 100, 100) inView:view animated:YES];
}
@end
